package com.whpost.service.service.stamp;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whpost.service.config.Wdpz;
import com.whpost.service.dao.stamp.StampHdMapper;
import com.whpost.service.dao.stamp.StampHdMbDybMapper;
import com.whpost.service.dao.stamp.StampHdMbMapper;
import com.whpost.service.dao.stamp.StampXmMapper;
import com.whpost.service.dao.t.TDelDao;
import com.whpost.service.entity.stamp.StampHd;
import com.whpost.service.entity.stamp.StampHdMb;
import com.whpost.service.entity.stamp.StampHdMbDyb;
import com.whpost.service.entity.stamp.StampXm;
import com.whpost.service.entity.t.TCzy;
import com.whpost.service.entity.t.TDel;
import com.whpost.service.entity.tools.ListInfo;
import com.whpost.service.entity.tools.PageInfo;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.service.t.FileService;
import com.whpost.service.service.t.TApiNonceService;
import com.whpost.service.tools.QRCodeGenerator;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StampHdMbServices extends BaseServices {

    @Resource
    private StampHdMbDybMapper stampHdMbDybMapper;
    @Resource
    private StampHdMapper stampHdMapper;
    @Resource
    private StampHdMbMapper stampHdMbMapper;
    @Resource
    private TApiNonceService tApiNonceService;
    @Resource
    private Wdpz wdpz;
    @Resource
    private FileService fileService;
    @Resource
    private TDelDao tDelDao;

    @Override
    public ResultInfo info(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",null);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    public ResultInfo query(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String curpage = "",pagesize="",mblx="";
            QueryWrapper<StampHdMb> queryWrapper = new QueryWrapper<>();
            if (jsonObject.containsKey("curpage")) {
                curpage = jsonObject.getString("curpage");
            }
            if (jsonObject.containsKey("pagesize")) {
                pagesize = jsonObject.getString("pagesize");
            }
            if (jsonObject.containsKey("mblx")) {
                mblx = jsonObject.getString("mblx");
            }


            if (StringUtils.isEmpty(curpage)) curpage = "1";
            if (StringUtils.isEmpty(pagesize)) pagesize = "10";

            Page<StampHdMb> page = new Page<>( Integer.parseInt(curpage),  Integer.parseInt(pagesize));

            ListInfo<StampHdMb> stampHdMbListInfo = new ListInfo<>();

            if (!StringUtils.isEmpty(mblx)){
                queryWrapper.eq("lx",mblx);
            }

            queryWrapper.eq("t_czy_id",loginId);

            queryWrapper.orderByDesc("id");

            IPage<StampHdMb> stampHdMbIPage = stampHdMbMapper.selectPage(page,queryWrapper);

            PageInfo pageInfo = new PageInfo();
            pageInfo.setTotal(stampHdMbIPage.getTotal());
            pageInfo.setCurPage(stampHdMbIPage.getCurrent());
            pageInfo.setPageSize(stampHdMbIPage.getSize());
            pageInfo.setPageTotal(stampHdMbIPage.getPages());

            stampHdMbListInfo.setPageInfo(pageInfo);

            List<StampHdMb> stampHdMbList = stampHdMbIPage.getRecords();

            // 循环遍历 List 并改变每个对象的 age 属性
            for (StampHdMb stampHdMb : stampHdMbList) {
                stampHdMb.setUrlId(ToolBean.getEncode(stampHdMb.getId()));
                stampHdMb.setId(null);
            }

            stampHdMbListInfo.setListInfo(stampHdMbList);
            stampHdMbListInfo.setUserId(loginId);

            //查询条件的值
            Map<String,Object> cxtjMap = new HashMap<>();
            cxtjMap.put("mblx",mblx);

            //返回前端的内容
            Map<String,Object> rtnMap = new HashMap<>();
            rtnMap.put("cxjg",stampHdMbListInfo);
            rtnMap.put("cxtj",cxtjMap);

            ResultInfo resultInfo = new ResultInfo(0, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }
    }

    @Override
    @Transactional
    public ResultInfo save(String loginId, List<MultipartFile> file, String data) {
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            JSONObject jsonObject = getDataStr(data,loginId);
            String lx="",id="",nonce_ms="",nonce_zhi="",mblx="";
            if (jsonObject.containsKey("lx")) {
                lx = jsonObject.getString("lx");
            }
            if (jsonObject.containsKey("id")) {
                id = jsonObject.getString("id");
            }
            if (jsonObject.containsKey("mblx")) {
                mblx = jsonObject.getString("mblx");
            }
            if (StringUtils.isEmpty(mblx)){
                return new ResultInfo(500,"关键参数信息丢失！",null);
            }
            if (jsonObject.containsKey("nonce_ms")) {
                nonce_ms = jsonObject.getString("nonce_ms");
            }
            if (jsonObject.containsKey("nonce_zhi")) {
                nonce_zhi = jsonObject.getString("nonce_zhi");
            }

            //校验nonce
            ResultInfo ResultInfoCheckNonce = new ResultInfo();
            ResultInfoCheckNonce = tApiNonceService.checkNonce(nonce_ms,loginId,nonce_zhi,"stampmb.save");

            if (ResultInfoCheckNonce.getCode()!=200)
            {
                return ResultInfoCheckNonce;
            }

            TCzy tCzy = gettCzyDao().getCzyById(loginId);

            String os = System.getProperty("os.name");
            String picPathReal = "";
            if (os != null && os.contains("Windows")) {
                //System.out.println("Windows");
                picPathReal = "d:\\stamp\\mb\\"+mblx+"\\";
            } else {
                //linux
                picPathReal = "/home/stamp/mb/"+mblx+"/";
            }
            StampHdMb stampHdMb = new StampHdMb();
            if (null!=file){
                for (MultipartFile wj : file) {
                    if (StringUtils.isEmpty(wj.getOriginalFilename())){
                        continue;
                    }
                    //保存模版
                    stampHdMb = new StampHdMb();
                    stampHdMb.setName("");
                    stampHdMb.setLx(mblx);
                    stampHdMb.setTCzyId(tCzy.getId());
                    stampHdMb.setTXzjgId(tCzy.getXzjgId());
                    stampHdMbMapper.insert(stampHdMb);

                    String wjm = String.valueOf(stampHdMb.getId()) + ".png";
                    String wjm_slt = String.valueOf(stampHdMb.getId()) + "_slt.png";

                    stampHdMb.setMblj(wjm);
                    stampHdMb.setMblj1(wjm_slt);
                    stampHdMbMapper.updateById(stampHdMb);

                    fileService.uploadFileSlt(wj, picPathReal, wjm,wjm_slt,mblx);
                }
            }

            return new ResultInfo(0,"操作成功！",null);

        }
    }

    @Override
    @Transactional
    public ResultInfo del(String loginId, Map<String, Object> map) {
        JSONObject jsonObject = getData(map,loginId);
        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(500,"用户信息丢失！",null);
        }else{
            String ids = "";
            if (jsonObject.containsKey("ids")) {
                ids = jsonObject.getString("ids");
            }
            String [] code = ids.split(",");
            int i=0;
            String str="";

            TCzy tCzy = gettCzyDao().getCzyById(loginId);
            StampHdMb stampHdMb = new StampHdMb();

            for(i=0;i<code.length;i++)
            {
                if (code[i].equals("")) {
                    continue;
                }
                String id = null;
                try {
                    ToolBean.info("code[i]准备解密："+code[i]);
                    id = Url.decrypt(java.net.URLDecoder.decode(code[i],"utf-8"));
                    ToolBean.info("code[i]准备解密后："+id);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("");
                }

                stampHdMb = new StampHdMb();
                stampHdMb = stampHdMbMapper.selectById(id);

                //项目经理和操作员职工信息一致的，才能删除！
                if (!stampHdMb.getTCzyId().equals(tCzy.getId())){
                    str+=stampHdMb.getName()+"[非本人上传的模版，无法删除]，";
                    continue;
                }

                long sl = stampHdMbDybMapper.selectCount(new QueryWrapper<StampHdMbDyb>().eq("mb_id",id));
                if (sl>0) {
                    str+= id+"，";
                    continue;
                }

                TDel tDel = new TDel();
                try {
                    String picPathReal = "";
                    String picSltPathReal = "";
                    String os = System.getProperty("os.name");
                    if (os != null && os.contains("Windows")) {
                        //System.out.println("Windows");
                        picPathReal = "d:\\stamp\\mb\\" + stampHdMb.getLx() + "\\" + stampHdMb.getMblj();
                        picSltPathReal = "d:\\stamp\\mb\\" + stampHdMb.getLx() + "\\" + stampHdMb.getMblj1();
                    } else {
                        //linux
                        picPathReal = "/home/stamp/mb/" + stampHdMb.getLx() + "/" + stampHdMb.getMblj();
                        picSltPathReal = "/home/stamp/mb/" + stampHdMb.getLx() + "/" + stampHdMb.getMblj1();
                    }
                    tDel = new TDel();
                    tDel.setLj(picPathReal);
                    tDel.setLx("1");
                    tDelDao.insert(tDel);

                    tDel = new TDel();
                    tDel.setLj(picSltPathReal);
                    tDel.setLx("1");
                    tDelDao.insert(tDel);

                    File file = new File(picPathReal);
                    if(file.exists()){
                        ToolBean.info("StampHdMbServices.delCodes准备删除["+picPathReal+"]，删除结果:"+file.delete());
                    }

                    File fileSlt = new File(picSltPathReal);
                    if(fileSlt.exists()){
                        ToolBean.info("StampHdMbServices.delCodes准备删除["+picSltPathReal+"]，删除结果:"+fileSlt.delete());
                    }
                    stampHdMbMapper.deleteById(id);
                }catch (Exception e){
                    ToolBean.info("StampHdMbServices.delCodes图片删除发生错误："+e.toString());
                }
            }
            ResultInfo resultInfo;
            if (str.length()>0) {
                str = str.substring(0,str.length()-1);
            }
            if (!StringUtils.isEmpty(str))
            {
                str="["+str+"]包含活动信息，无法删除！";
                resultInfo = new ResultInfo(500, str,null);
            }
            else {
                resultInfo = new ResultInfo(0, "删除完成，如果没有删除掉的，请重试!",null);;
            }
            return backRtn(new ResultInfo(0, str,null),loginId);
        }
    }
}
